﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using OnlineSchool.Web.ViewModels;
using OnlineSchool.Domain.Commands;
using OnlineSchool.Core.Common;
using OnlineSchool.Web.Core.Extensions;
using OnlineSchool.CommandProcessor.Dispatcher;
using OnlineSchool.Data.Repositories;
using OnlineSchool.Data.Interfaces;
using OnlineSchool.Web.Core.ActionFilters;
using System;
namespace OnlineSchool.Web.Controllers
{
    [CompressResponse]
    public class CategoryController : Controller
    {
        private readonly ICommandBus commandBus;
        private readonly ICategoryRepository categoryRepository;
        public CategoryController(ICommandBus commandBus, ICategoryRepository categoryRepository)
        {
            this.commandBus = commandBus;
            this.categoryRepository = categoryRepository;
        }       

        public ActionResult Index()
        {
            var categories = categoryRepository.GetAll();
            return View(categories);
        }       
        public ActionResult Details(int id)
        {
            return View();
        }
        public ActionResult Create()
        {
            return View();
        }
        [HttpGet]
        public ActionResult Edit(Guid id)
        {
            var category = categoryRepository.GetById(id);
            var viewModel = new CategoryFormModel(category);
            return View(viewModel);
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Save(CategoryFormModel form)
        {
            if(ModelState.IsValid)
            {
                var command = new CreateOrUpdateCategoryCommand(form.Id,form.Name, form.Description);
               IEnumerable<ValidationResult> errors=  commandBus.Validate(command);
                ModelState.AddModelErrors(errors);              
               if (ModelState.IsValid)
               {
                   var result = commandBus.Submit(command);
                   if (result.Success) return RedirectToAction("Index");                 
               }                
            }   
            //if fail
            if (Guid.Empty == form.Id)
                return View("Create",form);
            else
                return View("Edit", form);
        }         
        [HttpPost]
        public ActionResult Delete(Guid id)
        {
            var command = new DeleteCategoryCommand { Id = id };
            var result = commandBus.Submit(command);           
            var categories = categoryRepository.GetAll();
            return PartialView("_CategoryList", categories);      
        }       
    }
}
